package com.zheng.rpc.factories;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

/**
 * 获取单例对象的工厂类
 */
public final class SingletonFactory {
    private static volatile Map<String, Object> objectMap = new HashMap<>();

    private SingletonFactory() {
    }

    public static <T> T getInstance(Class<T> clazz) {
        String key = clazz.toString();
        Object instance = objectMap.get(key);
        if (instance == null) {
            synchronized (SingletonFactory.class) {
                instance = objectMap.get(key);
                if (instance == null) {
                    try {
                        //通过反射获取类的构造器
                        instance = clazz.getDeclaredConstructor().newInstance();
                        objectMap.put(key, instance);
                    } catch (IllegalAccessException | InstantiationException e) {
                        throw new RuntimeException(e.getMessage());
                    } catch (NoSuchMethodException | InvocationTargetException e) {
                        throw new RuntimeException(e.getMessage());
                    }
                }
            }
        }
        return clazz.cast(instance);
    }

}
